import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, Search } from 'antd-mobile'

import Icon from '@/components/MyIcon'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import {
  clearHistoryAction,
  delHistoryAction,
  saveHistoryAction,
  searchAction,
  searchResHistoryAction,
} from '@/store/action/search'
import { RootState } from '@/types/store'
const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const [search, setSearch] = useState('')

  // 搜索输入
  const { searchOption, searchHistory } = useSelector(
    (state: RootState) => state.searchReducer
  )
  // 是否正在搜索的标记
  const [isSearching, setIsSearching] = useState(false)
  const changeValue = (e: string) => {
    setSearch(e)

    run()
    if (e) {
      // 显示搜索建议
      setIsSearching(true)
    } else {
      // 显示搜索历史
      setIsSearching(false)
    }
  }
  // 防抖
  const { run } = useDebounceFn(
    () => {
      if (search) {
        dispatch(searchAction(search))
      }
    },
    { wait: 500 }
  )
  // 搜索
  const searchClick = async (value?: string) => {
    const bbq = value ? value : search
    dispatch(saveHistoryAction(bbq))
    setSearch(bbq)
    history.push('/search/result?q=' + bbq)
  }

  // 删除
  const delHistory = (index: number) => {
    dispatch(delHistoryAction(index))
  }
  // 清空
  const clear = () => {
    dispatch(clearHistoryAction())
  }
  useEffect(() => {}, [])
  // 高亮函数
  const highLight = (str: string) => {
    // 根据输入的内容 生成高亮的效果
    /*
      replace:
        参数1:字符串,或者正则
          new RegExp(search, 'gi') 正则表达式
            search: 找到和输入内容一致的文本
            'gi':全文匹配,忽略大小写
        参数2:替换的字符串或函数
          (match) => `<span>${match}</span>` 把匹配到的结果 包裹一层span并返回

        根据正则进行查找,查找到的结果,包裹上span并返回
    */
    return str?.replace(
      new RegExp(search, 'gi'),
      (match) => `<span>${match}</span>`
    )
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span
            className="search-text"
            onClick={() => {
              searchClick()
            }}
          >
            搜索
          </span>
        }
      >
        <Search
          value={search}
          onChange={changeValue}
          placeholder="请输入关键字搜索"
        />
      </NavBar>

      {true && (
        <div
          className="history"
          style={{
            display: isSearching ? 'none' : 'block',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clear}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {searchHistory.length > 0 &&
              searchHistory.map((v, i) => {
                return (
                  <span
                    key={i}
                    className="history-item"
                    onClick={() => {
                      searchClick(v)
                    }}
                  >
                    <span className="text-overflow">{v}</span>
                    <Icon
                      type="iconbtn_essay_close"
                      onClick={(e) => {
                        e.stopPropagation()
                        delHistory(i)
                      }}
                    />
                  </span>
                )
              })}
          </div>
        </div>
      )}

      <div className={classnames('search-result', isSearching ? 'show' : '')}>
        {searchOption.length > 0 &&
          searchOption.map((v, i) => {
            return (
              <div
                key={i}
                className="result-item"
                onClick={() => {
                  searchClick(v)
                }}
              >
                <Icon className="icon-search" type="iconbtn_search" />
                <div
                  className="result-value text-overflow"
                  dangerouslySetInnerHTML={{ __html: highLight(v) }}
                />
              </div>
            )
          })}
      </div>
    </div>
  )
}

export default SearchPage
